const Trade = require('../models/Trade');
const User = require('../models/User');
const StockService = require('./StockService');

class TradeService {
  constructor() {
    this.trades = new Map(); // 存储所有交易
    this.tradeCounter = 0;   // 交易ID计数器
  }

  // 创建交易
  createTrade(symbol, type, quantity, price) {
    // 验证股票是否存在
    const stock = StockService.getStockBySymbol(symbol);
    if (!stock) {
      throw new Error('Stock not found');
    }

    // 验证价格是否匹配当前市场价格（允许小幅度差异）
    const priceDifference = Math.abs(stock.currentPrice - price);
    if (priceDifference > stock.currentPrice * 0.01) { // 允许1%的差异
      throw new Error('Price does not match current market price');
    }

    this.tradeCounter++;
    const tradeId = `TRADE-${this.tradeCounter}`;
    const trade = new Trade(tradeId, symbol, type, quantity, price, new Date());
    
    this.trades.set(tradeId, trade);
    return trade.getInfo();
  }

  // 执行交易
  executeTrade(tradeId) {
    const trade = this.trades.get(tradeId);
    if (!trade) {
      throw new Error('Trade not found');
    }

    if (trade.status !== 'PENDING') {
      throw new Error('Trade is not in pending status');
    }

    trade.execute();
    return trade.getInfo();
  }

  // 取消交易
  cancelTrade(tradeId) {
    const trade = this.trades.get(tradeId);
    if (!trade) {
      throw new Error('Trade not found');
    }

    if (trade.status !== 'PENDING') {
      throw new Error('Trade is not in pending status');
    }

    trade.cancel();
    return trade.getInfo();
  }

  // 获取交易信息
  getTrade(tradeId) {
    const trade = this.trades.get(tradeId);
    return trade ? trade.getInfo() : null;
  }

  // 获取所有交易
  getAllTrades() {
    return Array.from(this.trades.values()).map(trade => trade.getInfo());
  }

  // 根据股票代码获取交易
  getTradesBySymbol(symbol) {
    const trades = [];
    this.trades.forEach(trade => {
      if (trade.symbol === symbol) {
        trades.push(trade.getInfo());
      }
    });
    return trades;
  }
}

module.exports = new TradeService(); // 单例模式